package com.rsstuan.xmpp.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.rsstuan.xmpp.XMPPMsgProcessor;

@SuppressWarnings("serial")
public class XMPPServlet extends HttpServlet {

	private Logger LOG = Logger.getLogger(XMPPServlet.class.getName());
	
	private XMPPService xmpp = XMPPServiceFactory.getXMPPService();
	
	private XMPPMsgProcessor proc = XMPPMsgProcessor.getInstance();

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Message msg = xmpp.parseMessage(request);
		JID fromJID = msg.getFromJid();
		String body = msg.getBody();
		LOG.info("receive xmpp message from" + fromJID.getId());
		//send("siqiguo@gmail.com", "hi");
		send(fromJID.getId(), proc.answer(body));
		
	}
	
	public void send(String to, String msgBody) {
		JID jid = new JID(to);
		Message msg = new MessageBuilder().withRecipientJids(jid)
		.withBody(msgBody)
		.build();
		boolean messageSent = false;
		if (xmpp.getPresence(jid).isAvailable()) {
			SendResponse status = xmpp.sendMessage(msg);
			messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
		}
		if (!messageSent) {
			LOG.log(Level.WARNING, "send xmpp message failed");
		}
		
	}
}
